<template>
    <el-row>
        <el-col :span="6">
            <list :title="'山区设计洪水计算'" @submitHandler="submitHandler"></list>
        </el-col>
        <el-col :span="18">
            <el-row>
                <el-col :span="6">
                    <RainfallResults @calcHandler="calcHandler" :data="apiResponse" :formValues1="formValues1"
                        :form="form" />
                </el-col>
                <el-col :span="18" style="padding-left: 10px">
                    <el-card>
                        <flowCalculator :resultsData="flowData" />
                        <DesignResultsTable :resultsData="resultsData" :showResultTable="true" @calcSubmitHandler="calcSubmitHandler" v-if="resultsData" />
                    </el-card>
                </el-col>
            </el-row>
        </el-col>
    </el-row>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted, nextTick } from "vue";
import * as echarts from "echarts";
import { ElLoading, ElMessageBox } from "element-plus";
import "element-plus/theme-chalk/dark/css-vars.css";
import list from "@/components/flood/list.vue";
import HttpService from "@/api/api";
import RainfallResults from "@/components/flood/RainfallResults.vue";
import DesignResultsTable from "@/components/flood/DesignResultsTable.vue";
import flowCalculator from "@/components/flood/flowCalculator.vue";

// 控制弹窗显示
const showModal = ref(false);
const openModal = function () {
    showModal.value = true;
}
// 表单和结果数据
const form = reactive({
    F: 26.916, // 默认流域面积
    L: 7.905, // 默认河道长度
    J: 0.018, // 默认河道比降
    center_coords: "112.0,34.0", // 默认流域中心坐标
    R: 58.39, // 默认设计净雨总量
});

const results = reactive({
    design_tables: {
        design_net_rainfall: [],
        design_flood: [],
    },
    time_distribution: [],
    flood_process_line: [],
});
const resultsData = ref(null);
const loading = ref(false); // 加载状态
const theme = ref("dark"); // 默认主题
const flowData = ref(null)


const calcSubmitHandler = function (params) {
  // 解析传递的 JSON 数据
  flowData.value = JSON.parse(params);


  // 处理数据，转换 `"-"` 为默认值
  const processedData = preprocessData(flowData.value);

  // 处理后的数据可以直接传递到其他逻辑或组件
  flowData.value = processedData;
 
};

function preprocessData(data) {
  // 深拷贝数据，避免直接修改原始数据
  const processedData = JSON.parse(JSON.stringify(data));

  // 遍历对象并处理
  const processValue = (value) => {
    if (value === "-") return 0; // 将 `"-"` 替换为 0
    if (typeof value === "object" && value !== null) return preprocessData(value); // 递归处理嵌套对象
    return value; // 返回原值
  };

  if (Array.isArray(processedData)) {
    return processedData.map((item) => processValue(item));
  } else if (typeof processedData === "object" && processedData !== null) {
    Object.keys(processedData).forEach((key) => {
      processedData[key] = processValue(processedData[key]);
    });
    return processedData;
  }

  return processedData; // 如果不是对象或数组，直接返回
}

// 提交计算方法
async function submitForm() {
    loading.value = true;
    const loadingInstance = ElLoading.service({
        lock: true,
        text: "正在计算中，请稍候...",
        background: "rgba(0, 0, 0, 0.7)",
    });

    try {
        const response = await fetch("http://123.57.240.141:5001/api/calculate", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({
                F: parseFloat(form.F as unknown as string),
                L: parseFloat(form.L as unknown as string),
                J: parseFloat(form.J as unknown as string),
                center_coords: form.center_coords.split(",").map(Number),
                R: parseFloat(form.R as unknown as string),
            }),
        });

        if (!response.ok) {
            alert("后端接口返回错误，请检查服务器！");

            return;
        }

        const data = await response.json();
        if (
            data &&
            data.design_tables &&
            data.time_distribution &&
            data.flood_process_line
        ) {
            results.design_tables = data.design_tables;
            results.time_distribution = data.time_distribution;
            results.flood_process_line = data.flood_process_line;

            // 渲染洪水过程线图
            await nextTick();
            renderFloodProcessChart();
        } else {
            alert("后端返回的数据结构不完整，请检查后端逻辑！");
        }
    } catch (error) {
        alert("请求失败，请检查网络或后端服务器！");
    } finally {
        setTimeout(() => {
            loading.value = false;
            loadingInstance.close();
        }, 500);
    }
}

// 渲染洪水过程线图
function renderFloodProcessChart() {
    const chart = echarts.init(
        document.getElementById("flood-process-chart") as HTMLElement
    );
    const option = {
        title: { text: "设计洪水过程线" },
        tooltip: { trigger: "axis" },
        xAxis: {
            type: "category",
            name: "时间 (T_i, h)",
            data: results.flood_process_line.map((item) => item["Time (T_i, h)"]),
        },
        yAxis: { type: "value", name: "流量 (Q_i, m³/s)" },
        series: [
            {
                data: results.flood_process_line.map(
                    (item) => item["Flow (Q_i, m³/s)"]
                ),
                type: "line",
                smooth: true,
                lineStyle: { width: 2 },
                areaStyle: {},
            },
        ],
    };
    chart.setOption(option);
}

// API 响应数据
const apiResponse = ref({
    chart_info: {
        alphas: [0.539178584, 0.539178584, 0.600393295, 0.679885224],
        area: 5,
        area_name: "山丘V区",
        contours: [
            {
                key: 8402,
                name: "年最大10min点雨量均值",
                value: 12.499999999999998,
                var: "yl_1",
            },
            {
                key: 8403,
                name: "年最大10min点雨量Cv",
                value: 0.5,
                var: "cv_1",
            },
            {
                key: 8405,
                name: "年最大1h点雨量均值",
                value: 30.00992261911459,
                var: "yl_2",
            },
            {
                key: 8406,
                name: "年最大1h点雨量Cv",
                value: 0.571264752536401,
                var: "cv_2",
            },
            {
                key: 8408,
                name: "年最大6h点雨量均值",
                value: 47.93489650355972,
                var: "yl_3",
            },
            {
                key: 8409,
                name: "年最大6h点雨量Cv",
                value: 0.5590333360009575,
                var: "cv_3",
            },
            {
                key: 8411,
                name: "年最大24h点雨量均值",
                value: 60.000000000000014,
                var: "yl_4",
            },
            {
                key: 8412,
                name: "年最大24h点雨量Cv",
                value: 0.5,
                var: "cv_4",
            },
            {
                key: 8421,
                name: "暴雨递减指数n1",
                value: 0.6,
                var: "n1",
            },
            {
                key: 8422,
                name: "暴雨递减指数n2",
                value: 0.75,
                var: "n2",
            },
            {
                key: 8423,
                name: "暴雨递减指数n3",
                value: 0.8,
                var: "n3",
            },
        ],
        imax: 55,
        m: 3.2883832734853775,
        mu: 5,
        theta: 1608.18233712727,
    },
    session: {
        alphas: [0.539178584, 0.539178584, 0.600393295, 0.679885224],
        imax: 55,
        lat: 34.619937896728516,
        lon: 110.6001968383789,
        m: 3.2883832734853775,
        mu: 5,
        theta: 1608.18233712727,
    },
});
const formValues1 = ref({});
// 定义表单提交处理函数
const submitHandler = async function (formValues) {

    // 提取参数并准备发送给后端接口的格式
    const params = {
        coord: formValues.center_coords, // 经纬度坐标
        f: formValues.F, // 流域面积
        l: formValues.L, // 流域长度
        j: formValues.J, // 降雨强度
    };
    formValues1.value = params;
    HttpService.floodManage.floodParams(
        params,
        (res) => {
            if (res.status == 200) {
                /* apiResponse.value.chart_info.alphas中的值没有更新   theta 的值没有更新*/
                apiResponse.value = { ...apiResponse.value, ...res.data };
                console.log("Updated apiResponse:", apiResponse.value);
            }
        },
        (error) => {
            ElMessageBox({
                message: error.data.error,
                type: "warning",
            });
        }
    );
};

const calcHandler = function (params) {
    params.formValues1 = formValues1.value;

    // 检查 `apiResponse` 是否有值
    if (!apiResponse.value) {
        ElMessageBox({
            message: "数据加载失败，请先获取暴雨参数。",
            type: "warning",
        });
        return;
    }

    // 动态从 `apiResponse` 中提取参数
    const chartInfo: any = apiResponse.value.chart_info || {};
    const session: any = apiResponse.value.session || {};

    // 转换设计频率为后端需要的格式
    const formattedFrequency = params.frequency.map((freq) => {
        const value = parseFloat(freq.replace("%", "")); // 去掉百分号
        return `p_${Math.round(100 / value)}`; // 转换为 p_x 格式
    });

    // 设置默认值函数
    const setDefault = (value, defaultValue) => {
        return value !== undefined && value !== null ? value : defaultValue;
    };

    // 组装请求数据
    const requestData = {
        is_use_tu_n: setDefault(params.isUseTuN, 0),
        k: parseFloat(setDefault(params.csCv, 3.5)),
        frequency: formattedFrequency,
        imax: setDefault(params.imax, chartInfo.imax || 50),
        theta: chartInfo.theta,
        area: setDefault(params.area, chartInfo.area || 4),
        ppa_r_id: setDefault(params.area, chartInfo.area || 4),
        m: setDefault(params.m, chartInfo.m || 1.473),
        mu: setDefault(params.mu, chartInfo.mu || 3.0),
        alpha_0: chartInfo.alphas?.[0],
        alpha_1: chartInfo.alphas?.[1],
        alpha_2: chartInfo.alphas?.[2],
        alpha_3: chartInfo.alphas?.[3],
        lon: setDefault(params.lon, session.lon || 112.0),
        lat: setDefault(params.lat, session.lat || 34.0),
        f: Math.max(parseFloat(setDefault(params.formValues1.f, 39.509)), 1e-6),
        l: parseFloat(setDefault(params.formValues1.l, 14.290)),
        j: Math.max(parseFloat(setDefault(params.formValues1.j, 0.01474878)), 1e-6),
        // 动态提取暴雨递减指数和点雨量参数
        n1: chartInfo.contours?.find((item) => item.var === "n1")?.value || 0.556,
        n2: chartInfo.contours?.find((item) => item.var === "n2")?.value || 0.702,
        n3: chartInfo.contours?.find((item) => item.var === "n3")?.value || 0.751,
        yl_1: chartInfo.contours?.find((item) => item.var === "yl_1")?.value || 15.004,
        cv_1: chartInfo.contours?.find((item) => item.var === "cv_1")?.value || 0.446,
        yl_2: chartInfo.contours?.find((item) => item.var === "yl_2")?.value || 36.063,
        cv_2: chartInfo.contours?.find((item) => item.var === "cv_2")?.value || 0.537,
        yl_3: chartInfo.contours?.find((item) => item.var === "yl_3")?.value || 59.96,
        cv_3: chartInfo.contours?.find((item) => item.var === "cv_3")?.value || 0.6,
        yl_4: chartInfo.contours?.find((item) => item.var === "yl_4")?.value || 82.161,
        cv_4: chartInfo.contours?.find((item) => item.var === "cv_4")?.value || 0.55,
    };

    // 调用接口
    HttpService.floodManage.floodCalc(
        requestData,
        (res) => {
            if (res.status === 200) {
                try {
                    let jsonData = typeof res.data === "string" ? res.data : JSON.stringify(res.data);
                    jsonData = jsonData.replace(/NaN|Infinity|-Infinity/g, "null");
                    resultsData.value = JSON.parse(jsonData);
                } catch (e) {
                    console.error("数据解析失败:", e.message);
                    ElMessageBox({
                        message: "数据解析失败，请稍后重试！",
                        type: "error",
                    });
                }
            }
        },
        (error) => {
            ElMessageBox({
                message: error?.data?.error || "请求失败，请稍后重试！",
                type: "warning",
            });
            console.error("API Error:", error);
        }
    );
};

</script>

<style scoped lang="scss">
.main-card {
    overflow: auto;
}

.header-title {
    text-align: center;
    margin-bottom: 20px;
    font-size: 24px;
    font-weight: bold;
    position: relative;
}

h2 {
    margin-bottom: 20px;
}

.form-container {
    margin-bottom: 20px;
}

.table-container {
    margin-top: 20px;
}
</style>
